package ch02.sl;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * DOM 解析
 */
public class Test_DOM {
    String url="src/ch02/sl/ch02_book.xml";
    Document doc=null;
    @Before  //在...之前
    public void init() throws ParserConfigurationException, IOException, SAXException {
        //加载xml文件
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder =fac.newDocumentBuilder();
        doc =builder.parse(url);
        System.out.println("文档加载成功");
    }

    @Test
    public void sl1() throws ParserConfigurationException, IOException, SAXException, TransformerException {

        //通过指定节点名去获取值
       /* NodeList nodeList = doc.getElementsByTagName("author");
        System.out.println(nodeList.item(0).getTextContent());*/

        //根据节点名称获取节点列表
        //得到根节点  getElementsByTagName
        NodeList nodeList = doc.getElementsByTagName("book");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node=nodeList.item(i); //解析空格
            Element ele = (Element) node; //忽略空格

            System.out.println("节点名称"+ele.getNodeName());
            String id=ele.getAttribute("id");
            System.out.println("\t属性:Id"+ " , 值: "+ id );

            //得到子节点,然后遍历
            NodeList childNodes= ele.getChildNodes();
            System.out.println("\t-----------子节点列表-----------");
            for (int j = 0; j < childNodes.getLength(); j++) {
                Element childEle= (Element) childNodes.item(j);
                if (childEle.getNodeType() == Node.ELEMENT_NODE){
                    /*if ("author".equals(childEle.getNodeName())  &&
                       "曹阿玉".equals(childEle.getTextContent()) ){
                      childEle.setTextContent("曹董事长");
                        saveXml(url,doc); //保存修改的操作
                    }*/
                    System.out.println("\t"+childEle.getNodeName()+":"+childEle.getTextContent());
                }
            }
            System.out.println("----------------------------------------");
        }
        System.out.println("end");
    }

    @Test
    public void add() throws FileNotFoundException, TransformerException {
        //定义个book节点
        Element book = doc.createElement("book");
        book.setAttribute("id","bk003");

        //定义3个子节点
        Element title = doc.createElement("title");
        title.setTextContent("框架基础");

        Element author = doc.createElement("author");
        author.setTextContent("李小群");

        Element desc = doc.createElement("desc");
        desc.setTextContent("看不懂的书");

        //绑定父子关系
        book.appendChild(title);
        book.appendChild(author);
        book.appendChild(desc);

        //找到books
        Element root_books = (Element) doc.getElementsByTagName("books").item(0);
        //book 追加到 books
        root_books.appendChild(book);
        //保存
        saveXml(url,doc);
    }


    @Test
    public void del() throws FileNotFoundException, TransformerException {
        NodeList list = doc.getElementsByTagName("desc");
        //System.out.println(list.item(1).getTextContent());
        Node node = list.item(1);
        Element ele = (Element) node;
        //ele.getParentNode().removeChild(node);  //删节点
        ele.removeAttribute("bid");  //删属性

        saveXml( url, doc);
    }
    public void saveXml(String url,Document doc) throws TransformerException, FileNotFoundException {
        TransformerFactory transFac = TransformerFactory.newInstance();
        Transformer trans =transFac.newTransformer();
        //设置编码
        trans.setOutputProperty(OutputKeys.ENCODING,"utf-8"); //gb2312
        StreamResult result = new StreamResult(new FileOutputStream(url));
        //dom -> xml
        DOMSource source = new DOMSource(doc);
        trans.transform(source,result);
    }
}
